import 'package:chat_ai_demo/db/db_manage.dart';
import 'package:chat_msg_demo/model/message_model.dart';
import 'package:flutter/cupertino.dart';

abstract class IMessage {
  Future<void> sendMessage(MessageModel model);
  Future<int> deleteMessage(int id);
  Future<void> update(MessageModel model);
  Future<List<MessageModel>> getAllMessage();
  // 分页查询
  Future<List<MessageModel>> getMessage({int pageIndex = 1, int pageSize = 20});
  Future<int> getMessageCount();
}

abstract class ITable {
  late String tableName;
}

class MessageDao implements IMessage, ITable {
  final int cid;
  final DBManage storage;

  @override
  String tableName = '';

  MessageDao(this.storage, {required this.cid})
    : tableName = tableNameByCid(cid) {
    debugPrint('init $tableName');
    storage.db.execute('''
      CREATE TABLE IF NOT EXISTS $tableName (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        content TEXT,
        ownerName TEXT,
        avatar TEXT,
        ownerType INTEGER,
        lastMessage TEXT
      )
    ''');
  }

  static String tableNameByCid(int cid) {
    return 'tb_$cid';
  }

  @override
  Future<int> deleteMessage(int id) {
    return storage.db.delete(tableName, where: 'id=$id');
  }

  @override
  Future<List<MessageModel>> getAllMessage() async {
    var res = await storage.db.rawQuery(
      'select * from $tableName order by id asc',
    );
    var list = res.map((item) => MessageModel.fromJson(item)).toList();
    return list;
  }

  @override
  Future<List<MessageModel>> getMessage({
    int pageIndex = 1,
    int pageSize = 20,
  }) async {
    var offset = (pageIndex - 1) * pageSize;
    var res = await storage.db.rawQuery(
      'select * from $tableName order by id desc limit $pageSize offset $offset',
    );
    var list = res.map((item) => MessageModel.fromJson(item)).toList();
    return List.from(list.reversed);
  }

  @override
  Future<int> getMessageCount() async {
    var res = await storage.db.query(tableName, columns: ['COUNT(*) as count']);
    return res.first['count'] as int;
  }

  @override
  Future<void> sendMessage(MessageModel model) async {
    debugPrint('insert $tableName');
    await storage.db.insert(tableName, model.toJson());
  }

  @override
  Future<void> update(MessageModel model) async {
    await storage.db.update(
      tableName,
      model.toJson(),
      where: 'id=?',
      whereArgs: [model.id],
    );
  }

  Future<void> clearMessages() async {
    await storage.db.delete(tableName, where: 'cid = ?', whereArgs: [cid]);
  }
}
